package cn.epet.dao.implement.database;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.epet.dao.IPetDao;
import cn.epet.model.entity_class.Pet;
import cn.epet.model.jdbc.ConnectionHandler;

public class PetDaoMysqlImpl extends BaseDao implements IPetDao {
	@Override
	public int updatePet(Pet pet) throws Exception {
		String OWNER_IDstr = "null";
		String STORE_IDstr = "null";
		if (!(pet.getOWNER_ID() == 0)) {
			OWNER_IDstr = String.valueOf(pet.getOWNER_ID());
		}
		if (!(pet.getSTORE_ID() == 0)) {
			STORE_IDstr = String.valueOf(pet.getSTORE_ID());
		}
		String updateSql = "update `epet`.`pet` set `NAME`='" + pet.getNAME() + "',`TYPENAME`='" + pet.getTYPENAME()
				+ "',`HEALTH`=" + pet.getHEALTH() + ",`LOVE`=" + pet.getLOVE() + ",`BIRTHDAY`='"
				+ pet.getBIRTHDAY().toString() + "',`OWNER_ID`=" + OWNER_IDstr + ",`STORE_ID`=" + STORE_IDstr
				+ ",`PRICE`=" + pet.getPRICE() + " where `ID`=" + pet.getID() + ";";
		int num = super.update(updateSql);
		return num;
	}
	@Override
	public int NewPet(Pet pet) throws Exception {
		SimpleDateFormat sf=new SimpleDateFormat("yy/MM/dd");
		String updateSql = "insert `epet`.`pet`(`NAME`,`TYPENAME`,`HEALTH`,`LOVE`,`BIRTHDAY`,`OWNER_ID`,`STORE_ID`,`PRICE`) values"
				+ "('"+pet.getNAME()+"','"+pet.getTYPENAME()+"',1,100,'"+sf.format(new Date())+"',null,"+pet.getSTORE_ID()+","+pet.getPRICE()+");";
		int num = super.update(updateSql);
		return num;
	}
	@Override
	public List<Pet> getAllPets() {
		List<Pet> pets = new ArrayList<Pet>();
		Map<String, Pet> petByIdMap = new HashMap<>();
		// TODO Auto-generated method stub
		Statement st = null;
		Connection conn = null;
		ResultSet rs = null;
		try {
			String sql;
			conn = ConnectionHandler.getConnection();
			st = conn.createStatement();
			sql = "SELECT * FROM `epet`.`pet` ORDER BY `ID` ASC  LIMIT 0,50;";
			rs = st.executeQuery(sql);
			int ID;
			String NAME;
			String TYPENAME;
			int HEALTH;
			int LOVE;
			Date BIRTHDAY;
			int OWNER_ID;
			int STORE_ID;
			double PRICE;

			while (rs.next()) {
				ID = rs.getInt("ID");
				NAME = rs.getString("NAME");
				TYPENAME = rs.getString("TYPENAME");
				HEALTH = rs.getInt("HEALTH");
				LOVE = rs.getInt("LOVE");
				BIRTHDAY = rs.getDate("BIRTHDAY");
				OWNER_ID = rs.getInt("OWNER_ID");
				STORE_ID = rs.getInt("STORE_ID");
				PRICE = rs.getDouble("PRICE");
				Pet pet = new Pet(ID, NAME, TYPENAME, HEALTH, LOVE, BIRTHDAY, OWNER_ID, STORE_ID, PRICE);
				pets.add(pet);
				petByIdMap.put(String.valueOf(ID), pet);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ConnectionHandler.close(rs, st);
		}
		return pets;
	}

}
